/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 * [See end of file]
 */

package com.hp.hpl.jena.clusteredtdb.pgraph;


import static com.hp.hpl.jena.tdb.lib.NodeLib.decode;
import static com.hp.hpl.jena.tdb.lib.NodeLib.setHash;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.tdb.TDBException;
import com.hp.hpl.jena.tdb.base.record.Record;
import com.hp.hpl.jena.tdb.index.Index;
import com.hp.hpl.jena.tdb.lib.NodeLib;
import com.hp.hpl.jena.tdb.nodetable.NodeTableBase;
import com.hp.hpl.jena.tdb.store.Hash;
import com.hp.hpl.jena.tdb.store.NodeId;

public abstract class BulkNodeTableBase extends NodeTableBase implements BulkNodeTable {

	//public BulkObjectFile objects;
	protected void init(Index nodeToId, BulkObjectFile objectFile,
                        int nodeToIdCacheSize, int idToNodeCacheSize) {
		
		super.init(nodeToId, objectFile, nodeToIdCacheSize, idToNodeCacheSize);
		super.objects = objectFile;
	}
	
	public Map<NodeId, Node> retrieveNodesByNodeIds(Set<NodeId> ids) {
        return _retrieveNodesByNodeIds(ids);
    }
	
	protected Map<NodeId, Node> _retrieveNodesByNodeIds(Set<NodeId> ids) {
		HashMap<NodeId,Node> nodeMap = new HashMap<NodeId,Node>();
		Node n;
//		TODO: synchronisation here needs examining.  Too simplistic for multi-computer scenario?
		synchronized (this)
		{
			Iterator<NodeId> it = ids.iterator();
			while(it.hasNext()) {
				//NodeId id = ids.get(i);
				NodeId id = it.next();
				if ( id == NodeId.NodeDoesNotExist ) {
					nodeMap.put(id, null);
					it.remove();
					continue;
				} 
				if ( id == NodeId.NodeIdAny ) {
					nodeMap.put(id, null);
					it.remove();
					continue;
				}

				// 	Inline?
				n = NodeId.extract(id) ;
				if ( n != null ) {
					nodeMap.put(id,n);
					it.remove();
					continue;
				}
				n = cacheLookup(id) ;
				if ( n != null ) {
					nodeMap.put(id,n);
					it.remove();
					System.err.println("FOUND!");
					continue;
				}
			}

			nodeMap.putAll(readNodesByNodeIds(ids));
			Iterator<NodeId> nodeMapIt = nodeMap.keySet().iterator();
			while(nodeMapIt.hasNext()) {
				NodeId nid = nodeMapIt.next();
				cacheUpdate(nodeMap.get(nid), nid);
			}
				
			return nodeMap;
		}
	}

	//TODO: kludgy.  clean up
    protected Map<NodeId,Node> readNodesByNodeIds(Set<NodeId> ids) {
		
		Map<NodeId,String> obs = ((BulkObjectFile)objects).readBulk(ids);
		HashMap<NodeId,Node> nodeMap = new HashMap<NodeId,Node>();
		Iterator<NodeId> it = obs.keySet().iterator();
		while(it.hasNext()) {
			NodeId nid = it.next();
			nodeMap.put(nid, decode(obs.get(nid)));
		}
		return nodeMap;
	}

	public Map<NodeId, Node> nodeIdForNodes(Set<Node> nodes) {
		// TODO Auto-generated method stub
		return null;
	}

	//NB: alters state of 'nodes'
	//TODO kludgy, needs serious tidying.
	public Map<Node, NodeId> storeNodes(Set<Node> nodes) {
		HashMap<Node,NodeId> resultSet = new HashMap<Node,NodeId>();
		HashSet<String> nodeStrings = new HashSet<String>(nodes.size());
		Iterator<Node> it = nodes.iterator();
		synchronized (this) { //TODO Investigate synchronization strategies
			while(it.hasNext()) {
				Node node = it.next();
				if ( node == Node.ANY ) {
					resultSet.put(node,NodeId.NodeIdAny) ;
					it.remove();
					continue;
				}

				// Inline?
				NodeId nodeId = NodeId.inline(node) ;
				if ( nodeId != null ) {
					resultSet.put(node,nodeId) ;
					it.remove();
					continue;
				}


				// Check caches.
				nodeId = cacheLookup(node) ;
				if ( nodeId != null ) {
					resultSet.put(node,nodeId) ;
					it.remove();
					continue;
				}

				nodeId = accessIndex(node, false);
				if (nodeId != NodeId.NodeDoesNotExist) {
					resultSet.put(node,nodeId);
					it.remove();
					continue;
				}
				nodeStrings.add(NodeLib.encode(node));

			}

			//write nodes
			Map<String,NodeId> hm = ((BulkObjectFile)objects).writeBulk(nodeStrings);
			it = nodes.iterator();

			//update nodeid/hash table and add results to return set.
			while(it.hasNext()) {
				Node node = it.next();
				NodeId nid = hm.get(NodeLib.encode(node));
				resultSet.put(node, nid);
				writeIdToIdHashTable(nid,node);
				cacheUpdate(node, nid);
			}
		}
		return resultSet;

		
	}
	
	private void writeIdToIdHashTable(NodeId id, Node node) {
		Hash hash = new Hash(nodeHashToId.getRecordFactory().keyLength()) ;
        setHash(hash, node) ;
        byte k[] = hash.getBytes() ;        
        // Key only.
        Record r = nodeHashToId.getRecordFactory().create(k) ;
        
        id.toBytes(r.getValue(), 0) ;

        // Put in index - may appear because of concurrency
        if ( ! nodeHashToId.add(r) )
            throw new TDBException("NodeTableBase::nodeToId - record mysteriously appeared") ;
    
	}

	
}

/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
